package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.google.gson.internal.$Gson$Preconditions;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @DubboReference
    private UserLikeApi userLikeApi;
    @DubboReference
    private VisitorsApi visitorsApi;
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private FriendApi friendApi;

    //保存用户信息
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        } else {
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    //更新用户信息
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo, vo); //copy同名同类型的属性

        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    /**
     * 查看互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     */
    public PageResult findFriends(Integer page, Integer pagesize, String nickname, Integer type) {
        PageResult pr = null;
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();

        /**
         * 互相喜欢
         */
        if (type == 1) {
            //调用API查询当前用户的好友数据 -- List<Friend>
            List<Friend> list = friendApi.findByUserId(userId, page, pagesize);
            if (CollUtil.isEmpty(list)) {
                return new PageResult();
            }
            //2、提取数据列表中的好友id
            List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);
            UserInfo info = new UserInfo();
            info.setNickname(nickname);
            Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, info);
            //4、构造VO对象
            List<ContactVo> vos = new ArrayList<>();
            for (Friend friend : list) {
                UserInfo userInfo = map.get(friend.getFriendId());
                if (userInfo != null) {
                    ContactVo vo = ContactVo.init(userInfo);
                    vos.add(vo);
                }
            }
            pr = new PageResult(page, pagesize, 0, vos);
        }

        /**
         * 喜欢
         */

        if (type == 2) {
            //2、调用API查询当前用户的喜欢列表   106
            List<UserLike> list = userLikeApi.queryMyLikeList(userId, page, pagesize);
            if (CollUtil.isEmpty(list)) {
                return new PageResult();
            }
            //提取被用户喜欢的id列表
            List<Long> userIds = CollUtil.getFieldValues(list, "likeUserId", Long.class);
            UserInfo info = new UserInfo();
            info.setNickname(nickname);
            //根据被用户喜欢的id列表获取用户详情
            Map<Long, UserInfo> userMaps = userInfoApi.findByIds(userIds, info);
            //封装到vo
            List<ContactVo> vos = new ArrayList<>();
            for (UserLike userLike : list) {
                UserInfo userInfo = userMaps.get(userLike.getLikeUserId());
                if (userInfo != null) {
                    ContactVo vo = ContactVo.init(userInfo);
                    vos.add(vo);
                }
            }
            pr = new PageResult(page, pagesize, 0, vos);
        }

        /**
         * 粉丝
         */
        if (type == 3) {
            //2、调用API查询当前用户的粉丝列表
            List<UserLike> list = userLikeApi.queryMyFansList(userId, page, pagesize);
            if (CollUtil.isEmpty(list)) {
                return new PageResult();
            }
            //提取喜欢用户的id列表
            List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
            UserInfo info = new UserInfo();
            info.setNickname(nickname);
            //根据粉丝的id列表获取用户详情
            Map<Long, UserInfo> userMaps = userInfoApi.findByIds(userIds, info);
            //封装到vo
            List<ContactVo> vos = new ArrayList<>();
            for (UserLike userLike : list) {
                UserInfo userInfo = userMaps.get(userLike.getUserId());
                if (userInfo != null) {
                    ContactVo vo = ContactVo.init(userInfo);
                    vos.add(vo);
                }
            }
            pr = new PageResult(page, pagesize, 0, vos);
        }

        /**
         * 谁看过我
         */
        if (type == 4) {
            //2、调用API查询当前用户的访客列表
            List<Visitors> list = visitorsApi.queryMyVisitorsList(userId, page, pagesize);
            if (CollUtil.isEmpty(list)) {
                return new PageResult();
            }
            //3.提取访客的id列表
            List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
            //4.根据访客的id列表获取用户详情
            Map<Long, UserInfo> userMaps = userInfoApi.findByIds(userIds, null);
            //封装到vo
            ArrayList<ContactVo> vos = new ArrayList<>();
            for (Visitors visitors : list) {
                UserInfo userInfo = userMaps.get(visitors.getVisitorUserId());
                if (userInfo != null) {
                    ContactVo vo = ContactVo.init(userInfo);
                    int matchRate = visitors.getScore().intValue();
                    if (matchRate <= 99 && matchRate >= 30) {
                        vo.setMatchRate(matchRate);
                    }
                    vos.add(vo);
                }
            }
            pr = new PageResult(page, pagesize, 0, vos);
        }
        return pr;
    }

    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     *
     * @return
     */
    public CountsVo fingCount() {
        Long userId = UserHolder.getUserId();
        Integer eachlove = userLikeApi.eachOtherLikeUserCount(userId);
        Integer love = userLikeApi.LikeUserCount(userId);
        Integer fans = userLikeApi.fanCount(userId);
        CountsVo countsVo = new CountsVo();
        if (eachlove == 0 && love == 0) {
            countsVo.setEachLoveCount(0);
            countsVo.setLoveCount(0);
            countsVo.setFanCount(0);
        } else if (eachlove == 0 && love != 0 && fans != 0) {
            countsVo.setEachLoveCount(0);
            countsVo.setLoveCount(love);
            countsVo.setFanCount(fans);
        } else if (eachlove != 0 && love == 0 && fans != 0) {
            countsVo.setEachLoveCount(eachlove);
            countsVo.setLoveCount(0);
            countsVo.setFanCount(fans);
        } else if (eachlove != 0 && love != 0 && fans == 0) {
            countsVo.setEachLoveCount(eachlove);
            countsVo.setLoveCount(love);
            countsVo.setFanCount(0);
        } else {
            countsVo.setEachLoveCount(eachlove);
            countsVo.setLoveCount(love);
            countsVo.setFanCount(fans);
        }

        return countsVo;
    }
}
